<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="55%"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm" style="width: calc(100% - 20px); margin: auto" />

    <ActionAuth
      :moduleId="moduleId"
      :data="actionAuths"
      v-if="appMenuType === 0"
      @success="handleSuccess"
      :isModelBind="isModelBind"
    />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './post.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { addMenuApi, updateMenuApi, getMenuItemApi } from '/@/api/admin/menu';
  import ActionAuth from './components/ActionAuth.vue';

  export default defineComponent({
    name: 'PostDrawer',
    components: { BasicModal, BasicForm, ActionAuth },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const moduleId = ref();
      const isModelBind = ref(true);
      const actionAuths = ref<any>();

      const appMenuType = ref<number>(0);
      let updateInfo = {};
      const { createMessage } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
        labelWidth: 130,
        baseColProps: { span: 12 },
        schemas: formSchema((val) => {
          appMenuType.value = val;
        }),
        showActionButtonGroup: false,
      });

      async function getMenuItem(moduleId) {
        const res = await getMenuItemApi(moduleId);
        const { module, moduleUserTypes, usingHandles } = res;

        actionAuths.value = usingHandles || [];
        return { module, moduleUserTypes, usingHandles };
      }

      const [registerDrawer, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = data.isUpdate;

        if (unref(isUpdate)) {
          const { module } = await getMenuItem(data.record.moduleId);
          moduleId.value = data.record.moduleId;
          module.extMeta = JSON.stringify(module.extMeta || '{}');
          updateInfo = module;
          let bigMengImg =
            module.bigMengImg &&
            module.bigMengImg.split(',').map((i) => {
              return {
                url: i,
              };
            });
          let openBigMengImg =
            module.openBigMengImg &&
            module.openBigMengImg.split(',').map((i) => {
              return {
                url: i,
              };
            });

          setFieldsValue({
            ...module,
            bigMengImg,
            openBigMengImg,
          });
        }
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));
      function toJson(str) {
        try {
          return JSON.parse(str || '{}');
        } catch (e) {
          return {};
        }
      }
      async function handleSubmit() {
        try {
          const values = await validate();

          if (values.bigMengImg) {
            values.bigMengImg = values.bigMengImg.map((i) => i.url).toString();
          }
          if (values.openBigMengImg) {
            values.openBigMengImg = values.openBigMengImg.map((i) => i.url).toString();
          }

          setModalProps({ confirmLoading: true });
          // TODO custom api

          const apiFn = unref(isUpdate) ? updateMenuApi : addMenuApi;
          values.menuType = 2;
          values.client = 1;
          values.typeFlag = 0;
          values.modRight = 1;

          if (!unref(isUpdate)) {
            values.typeRight = 1;
            values.modRight = 1;
          }
          const extMeta = toJson(values.extMeta);
          const params = Object.assign(updateInfo, values, { extMeta });

          await apiFn(params);
          // updatePost
          closeModal();
          createMessage.success('操作成功');
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function handleSuccess() {
        getMenuItem(moduleId.value);
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        moduleId,
        isModelBind,
        handleSuccess,
        actionAuths,
        appMenuType,
        // treeData,
      };
    },
  });
</script>
